const { Service } = require('egg');

class CommentService extends Service {
    /**
     * 添加评论
     * @param {string} content 评论内容
     * @param {number} uid 发表评论的用户id
     * @param {number} bid 评论的哪篇博客id
     */
    async create({ content, uid, bid }) {
        let sql = 'insert into comment (content, uid, bid) values (?, ?, ?)';
        let params = [content, uid, bid];
        let res = await this.app.mysql.query(sql, params);
        return res;
    }

    /**
     * 获取某篇博客的评论列表
     * @param {number} bid 博客id
     */
    async readList(bid) {
        let sql = `
            select c.id, c.content, count(ruc.cid) as star, c.create_time, c.uid, c.bid, u.username, u.nickname
            from comment as c
            join user as u on c.uid = u.id
            left join r_user_comment as ruc on c.id = ruc.cid
            where c.bid = ?
            group by c.id
            order by count(c.id) desc, c.create_time asc;
        `;
        let params = [bid];
        let res = await this.app.mysql.query(sql, params);
        return res;
    }

    /**
     * 获取评论详情
     * @param {number} id 评论id
     */
    async find(id) {
        let sql = 'select * from comment where id = ?';
        let params = [id];
        let res = await this.app.mysql.query(sql, params);
        return res[0];
    }

    /**
     * 获取用户已点赞的评论
     * @param {number} uid 用户id
     */
    async liked(uid) {
        let sql = 'select cid from r_user_comment where uid = ?';
        let params = [uid];
        let res = await this.app.mysql.query(sql, params);
        return res;
    }

    /**
     * 用户是否点赞了某条评论
     * @param {number} uid 用户id
     * @param {number} cid 评论id
     */
    async isLiked({ uid, cid }) {
        let sql = `select count(*) as count from r_user_comment where uid = ? and cid = ?`;
        let params = [uid, cid];
        let res = await this.app.mysql.query(sql, params);
        return res[0].count > 0;
    }

    /**
     * 用户取消点赞某条评论
     * @param {number} uid 用户id
     * @param {number} cid 评论id
     */
    async unLike({ uid, cid }) {
        let sql = 'delete from r_user_comment where uid = ? and cid = ?';
        let params = [uid, cid];
        let res = await this.app.mysql.query(sql, params);
        return res;
    }

    /**
     * 用户点赞某条评论
     * @param {number} uid 用户id
     * @param {number} cid 评论id
     */
    async like({ uid, cid }) {
        let sql = 'insert into r_user_comment (uid, cid) values (?, ?)';
        let params = [uid, cid];
        let res = await this.app.mysql.query(sql, params);
        return res;
    }
}

module.exports = CommentService;
